package top.myhdg.bijou.part;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.http.SslError;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.MotionEvent;
import android.view.View;
import android.webkit.JsResult;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.ProgressBar;

import java.io.File;

import top.myhdg.bijou.R;

public class EnhanceWebView extends SwipeRefreshLayout
        implements SwipeRefreshLayout.OnRefreshListener,
        SwipeRefreshLayout.OnChildScrollUpCallback {

    private Context context;

    private MyHdgWebView webView;

    private ProgressBar progressBar;

    private LinearLayout linearLayout;

    public boolean dropDown = true;

    public EnhanceWebView(Context context) {
        super(context);
        this.context = context;

        //==========生成布局(容纳进度条和WebView)==========
        linearLayout = new LinearLayout(context);
        LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        linearLayout.setOrientation(LinearLayout.VERTICAL);
        linearLayout.setLayoutParams(params);
        addView(linearLayout);
        //==========生成布局(容纳进度条和WebView)==========

        setColorSchemeColors(Color.parseColor("#009385"), Color.parseColor("#BDE4E0"));

        if (!isInEditMode()) {//防止xml加载错误
            initProgressBar(context);
        }

        initWebView();
    }

    //初始化进度条
    private void initProgressBar(Context context) {
        progressBar = new ProgressBar(context, null, android.R.attr.progressBarStyleHorizontal);

        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, 4);
        progressBar.setLayoutParams(params);

        Drawable drawable;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
            drawable = context.getResources().getDrawable(R.drawable.progress_bar, null);
        } else {
            drawable = context.getResources().getDrawable(R.drawable.progress_bar);
        }
        progressBar.setProgressDrawable(drawable);

        linearLayout.addView(progressBar);
    }

    //初始化WebView
    private void initWebView() {
        webView = new MyHdgWebView(context);

        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, 0, 1.0f);
        webView.setLayoutParams(params);
        linearLayout.addView(webView);

        setOnRefreshListener(this);//添加下拉监听

        webView.setScrollViewListener(new MyHdgWebView.ScrollViewListener() {
            @Override
            public void onScrollChanged(WebView webView, int x, int y, int oldx, int oldy) {
                if (webView.getScrollY() == 0) {
                    EnhanceWebView.this.setEnabled(dropDown);
                } else {
                    EnhanceWebView.this.setEnabled(false);
                }
            }
        });

        WebSettings webSettings = webView.getSettings();
        webSettings.setUseWideViewPort(true); //设置是否支持HTML的“viewport”标签或者使用wide viewport
        webSettings.setLoadWithOverviewMode(true); // 缩放至屏幕的大小
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        webSettings.setSupportZoom(true); //支持缩放，默认为true。是下面那个的前提。
        webSettings.setBuiltInZoomControls(true); //设置内置的缩放控件。若为false，则该WebView不可缩放
        webSettings.setDisplayZoomControls(false); //false 隐藏原生的缩放控件
        webSettings.setAllowFileAccess(true); //设置可以访问文件
        webSettings.setDefaultTextEncodingName("utf-8");//设置编码格式
        webSettings.setDomStorageEnabled(true); // 开启 DOM storage API 功能
        webSettings.setDatabaseEnabled(true);   //开启 database storage API 功能
        webSettings.setAppCacheEnabled(true);//开启 Application Caches 功能
        webSettings.setGeolocationEnabled(true);//开启定位功能
        webSettings.setDatabaseEnabled(true);//启用数据库
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);//支持JS打开新窗口
        webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_COMPATIBILITY_MODE);

        //==========HTML5数据存储==========
        //有时候网页需要自己保存一些关键数据,Android WebView 需要自己设置
        if (isNetworkConnected(context)) {
            webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);//根据cache-control决定是否从网络上取数据。
        } else {
            webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);//没网，则从本地获取，即离线加载
        }
        File cacheDir = context.getCacheDir();
        if (cacheDir != null) {
            String appCachePath = cacheDir.getAbsolutePath();
            webSettings.setDomStorageEnabled(true);
            webSettings.setDatabaseEnabled(true);
            webSettings.setAppCacheEnabled(true);
            webSettings.setAppCachePath(appCachePath);
        }
        //==========HTML5数据存储==========
    }

    //==========下拉刷新==========
    @Override
    public void onRefresh() {
        webView.reload();
    }

    @Override
    public boolean canChildScrollUp(@NonNull SwipeRefreshLayout parent, @Nullable View child) {
        return webView.getScrollY() > 0;
    }
    //==========下拉刷新==========

    //实现一个基础的 WebViewClient ，如果有更多的需要，直接继承它
    public static class BaseWebViewClient extends WebViewClient {
        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {//处理https请求
            handler.proceed();    //忽略证书错误
            // handler.cancel();      //停止加载问题页面
            // handler.handleMessage(null);    //可做其他处理
        }

        @Override
        public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
            super.onReceivedHttpError(view, request, errorResponse);

//                Toast.makeText(MainActivity.this, "加载出错!\n错误信息:" + errorResponse.toString(), Toast.LENGTH_LONG).show();
        }

        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
            super.onReceivedError(view, request, error);

//                Toast.makeText(MainActivity.this, "加载出错!\n错误信息:" + error.getDescription() + "\n错误代码:" + error.getErrorCode(), Toast.LENGTH_LONG).show();
        }
    }

    //实现一个基础的 WebChromeClient ，如果有更多的需要，直接继承它
    public static class BaseWebChromeClient extends WebChromeClient {
        @Override
        public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
            return super.onJsAlert(view, url, message, result);
        }
    }

    //获取WebView高度
    public int getPageHeight() {
        return computeVerticalScrollRange();
    }

    //获取WebView宽度
    public int getPageWidth() {
        return computeHorizontalScrollRange();
    }

    //返回进度条给外部
    public ProgressBar getProgressBar() {
        return progressBar;
    }

    //返回WebView给外部
    public WebView getWebView() {
        return webView;
    }

    //判断是否联网
    public static boolean isNetworkConnected(Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            assert mConnectivityManager != null;
            NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
            return mNetworkInfo != null;
        }
        return false;
    }
}

class MyHdgWebView extends WebView {
    private ScrollViewListener scrollViewListener;

    public MyHdgWebView(Context context) {
        super(context);
        setBackgroundColor(getResources().getColor(R.color.Transparent));
    }

    interface ScrollViewListener {
        void onScrollChanged(WebView webView, int x, int y, int oldx, int oldy);
    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            //处理下拉刷新与WebView的冲突
            case MotionEvent.ACTION_DOWN:
                if (this.getScrollY() <= 0)
                    this.scrollTo(0, 1);
                break;
        }

        return super.onTouchEvent(event);
    }

    public void setScrollViewListener(ScrollViewListener scrollViewListener) {//暴露出滚动接口，解决API 23以下不能调用问题
        this.scrollViewListener = scrollViewListener;
    }

    @Override
    protected void onScrollChanged(int x, int y, int oldx, int oldy) {
        super.onScrollChanged(x, y, oldx, oldy);
        if (scrollViewListener != null) {
            scrollViewListener.onScrollChanged(this, x, y, oldx, oldy);
        }
    }
}

